package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import com.atguigu.util.MyClickHouseUtil;
import com.atguigu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hfh
 * @version 1.0
 * @date 2022/8/24 16:28
 */
public class DwsUserPageViewWindow {
    public static void main(String[] args) throws Exception {
        //获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //设置状态后端
        /*env.enableCheckpointing(5*60*1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setCheckpointTimeout(3*60*1000L);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO  3 读取页面数据 dwd_user_page_view
        String topicName = "dwd_traffic_page_log";
        String groupId = "dws_user_page_view_window";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        //TODO 4 过滤出首页page_id=home and source_detail 并转换为json
        SingleOutputStreamOperator<JSONObject> flatMap = streamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try{
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    JSONObject page = jsonObject.getJSONObject("page");
                    String page_id = page.getString("page_id");
                    if ("home".equals(page_id) || "course_detail".equals(page_id)) {
                        out.collect(jsonObject);
                    }
                }catch (Exception e){}
            }
        });

        //TODO 5 设置水位线
        SingleOutputStreamOperator<JSONObject> timestampsAndWatermarks = flatMap.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("ts");
                    }
                }));

        //TODO 根据mid分组，根据状态去重
        KeyedStream<JSONObject, String> keyedStream = timestampsAndWatermarks.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getJSONObject("common").getString("mid");
            }
        });

        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> flatmap1 = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TrafficHomeDetailPageViewBean>() {
            private ValueState<String> homeValueState = null;
            private ValueState<String> detailValueState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> homeState = new ValueStateDescriptor<>("homeState", String.class);
                homeState.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build());
                homeValueState = getRuntimeContext().getState(homeState);

                ValueStateDescriptor<String> detailState = new ValueStateDescriptor<>("detailState", String.class);
                detailState.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build());
                detailValueState = getRuntimeContext().getState(detailState);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                String pageId = value.getJSONObject("page").getString("page_id");
                String lastDt = DateFormatUtil.toDate(value.getLong("ts"));
                Long homeCount = 0L;
                Long detailCount = 0L;
                if ("home".equals(pageId)) {
                    if (homeValueState.value() == null || !lastDt.equals(homeValueState.value())) {
                        homeValueState.update(lastDt);
                        homeCount = 1L;
                    }
                } else {
                    if (detailValueState.value() == null || !lastDt.equals(detailValueState.value())) {
                        detailValueState.update(lastDt);
                        detailCount = 1L;
                    }
                }

                if (homeCount == 1L || detailCount == 1L) {
                    out.collect(new TrafficHomeDetailPageViewBean("", "", homeCount, detailCount, value.getLong("ts")));
                }
            }
        });

        //TODO 7 聚合统计点击次数
        AllWindowedStream<TrafficHomeDetailPageViewBean, TimeWindow> windowedStream = flatmap1.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10L)));

        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> reduce = windowedStream.reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
            @Override
            public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1, TrafficHomeDetailPageViewBean value2) throws Exception {
                value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                value1.setCourseDetailUvCt(value1.getCourseDetailUvCt() + value2.getCourseDetailUvCt());
                return value1;
            }
        }, new AllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow window, Iterable<TrafficHomeDetailPageViewBean> values, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                TrafficHomeDetailPageViewBean next = values.iterator().next();
                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                out.collect(next);
            }
        });

        reduce.print("home_detail>>>>>");

        //TODO 8 写出到clickhouse
        reduce.addSink(MyClickHouseUtil.<TrafficHomeDetailPageViewBean>getSink("insert into dws_user_page_view_window values(?,?,?,?,?)"));

        env.execute(groupId);
    }
}
